package cn.edu.swust.adressbook.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Objects;

import cn.edu.swust.adressbook.R;
import cn.edu.swust.adressbook.adapter.GroupSelectItemAdapter;
import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.bean.Group;
import cn.edu.swust.adressbook.service.IBaseService;
import cn.edu.swust.adressbook.service.impl.ContactServiceImpl;
import cn.edu.swust.adressbook.service.impl.GroupServiceImpl;

/**
 * @file 编辑联系人信息类
 * 此类可以对已有联系人信息进行修改并保存，修改包括（联系人姓名，公司，来电显示，电话号码，家庭电话，分组以及来电铃声）
 */

public class EditActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private IBaseService mContactService;
    private LinearLayout mCancel;///< 取消
    private TextView mFinish;///< 完成
    private EditText mName;///< 姓名
    private EditText mCompany;///< 公司
    private EditText mShow;///< 来电显示
    private ImageView mDeletePhoneNum;///< 删除电话号码
    private EditText mPhoneNumber;///< 电话号码
    private ImageView mDeleteHomeNum;///< 删除住宅号码
    private EditText mHomeNumber;///< 住宅电话
    private ImageView mDeleteGroup;///< 删除群组
    private ImageView mDeleteMusic;///< 删除铃声
    private EditText mMusic;///< 来电铃声
    private TextView mDelete;///< 删除联系人
    private Contact mPeople;///< 传过来的联系人对象
    private PopupWindow mPopWindow;          ///< 选择群组的浮框
    private Long mGroupId = null;            ///< 选择的群组ID
    private TextView mGroupSelect;           ///< 群组选择按钮
    private ListView mGroupSelectList;       ///< 群组选择列表
    private List<Group> mGroups;             ///< 群组列表
    private GroupSelectItemAdapter mGroupSelectItemAdapter; ///< 群组列表适配器


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        initView();
        setListener();
        initData();
    }

    /**
     * 初始化数据 mPeople，mContactService
     */
    private void initData(){
        Intent intent = getIntent();
        if(intent == null)
        {
            Toast.makeText(EditActivity.this,"获取联系人失败",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mPeople = (Contact)intent.getSerializableExtra(MainActivity.PERSON);
        if (mPeople == null) {
            Toast.makeText(EditActivity.this,"获取联系人失败",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        IBaseService baseService = new GroupServiceImpl(this);
        mGroupSelectItemAdapter = new GroupSelectItemAdapter(this);
        mGroupId = mPeople.getGroupId();
        Log.i("EditActivity","" + mGroupId);
        mGroups = baseService.getAll();
        Group group = new Group();
        group.setName("无");
        group.setId(-1L);
        mGroups.add(group);
        mGroupSelectItemAdapter.setGroups(mGroups);
        mContactService = new ContactServiceImpl(this);
        setViewContent();
    }

    /**
     *获取按钮
     */
    private void initView() {
        mCancel = (LinearLayout) findViewById(R.id.cancle_btn);
        mFinish = (TextView) findViewById(R.id.finish_btn);
        mName = (EditText) findViewById(R.id.input_name);
        mCompany = (EditText) findViewById(R.id.input_company);
        mShow = (EditText) findViewById(R.id.input_show);
        mDeletePhoneNum = (ImageView) findViewById(R.id.delete_phone_num);
        mPhoneNumber = (EditText) findViewById(R.id.input_phone_num);
        mDeleteHomeNum = (ImageView) findViewById(R.id.delete_home_num);
        mHomeNumber = (EditText) findViewById(R.id.input_home_num);
        mDeleteGroup = (ImageView) findViewById(R.id.delete_group);
        mGroupSelect = (TextView) findViewById(R.id.input_group);
        mDeleteMusic = (ImageView) findViewById(R.id.delete_music);
        mMusic = (EditText) findViewById(R.id.input_music);
        mDelete = (TextView) findViewById(R.id.delete_btn);

        //setViewContent();
    }

    /**
     * 给控件设置监听器
     */
    private void setListener() {
        mFinish.setOnClickListener(this);
        mCancel.setOnClickListener(this);
        mDeletePhoneNum.setOnClickListener(this);
        mDeleteHomeNum.setOnClickListener(this);
        mDeleteGroup.setOnClickListener(this);
        mDeleteMusic.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mGroupSelect.setOnClickListener(this);
    }

    /**
     * 更新Contact内容,更新联系人信息
     */
    public void setContent() {
        mPeople.setName(String.valueOf(mName.getText()));
        mPeople.setCompany(String.valueOf(mCompany.getText()));
        mPeople.setNotes(String.valueOf(mShow.getText()));
        mPeople.setPhoneNumber(String.valueOf(mPhoneNumber.getText()));
        mPeople.setPlaceOfCall(String.valueOf(mHomeNumber.getText()));
        mPeople.setGroupId(mGroupId);

    }

    /**
     * 将传过来的联系人信息填充到页面
     */
    public void setViewContent() {
        mName.setText(mPeople.getName());
        mCompany.setText(mPeople.getCompany());
        mShow.setText(mPeople.getNotes());
        mPhoneNumber.setText(mPeople.getPhoneNumber());
        mHomeNumber.setText(mPeople.getPlaceOfCall());
        mGroupSelect.setText(getGroupNameById());
    }

    /**
     * 根据ID得到分组名 null为空
     * @return 分组名
     */
    private String getGroupNameById() {
        if (mGroupId == null) {
            return "";
        }
        for (int i = 0; i < mGroups.size(); i++) {
            if (Objects.equals(mGroupId, mGroups.get(i).getId())) {
                return mGroups.get(i).getName();
            }
        }
        return "";
    }

    /**
     * 检验输入电话号码是否规范
     */
    public void checkPhoneNumber() {
       String number =  String.valueOf(mPhoneNumber.getText());
        if(number.length()!=11) {
            new  AlertDialog.Builder(this)
                    .setTitle("错误提示" )
                    .setMessage("您输入的电话号码有误！" )
                    .setNegativeButton("取消" , null)
                    .setPositiveButton("确认" ,  null )
                    .show();
        }
        else {
            setContent();
            mContactService.update(mPeople);
            finish();
        }
    }

    /**
     * 相应点击事件
     * @param v 点击的view
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancle_btn:
                finish();///< 结束当前页面的生命周期
                break;
            case R.id.finish_btn:
                checkPhoneNumber();
                break;
            case R.id.delete_phone_num:
                mPhoneNumber.setText(" ");
                break;
            case R.id.delete_home_num:
                mHomeNumber.setText(" ");
                break;
            case R.id.input_group:
                showPopupWindow();
                break;
            case R.id.delete_group:
                mGroupSelect.setText("");
                break;
            case R.id.delete_music:
                mMusic.setText(" ");
                break;
            case R.id.delete_btn:
                mContactService.delete(mPeople);
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 选择群组的浮框
     */
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(EditActivity.this).inflate(R.layout.activity_select_group_popupwindow, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setOutsideTouchable(true);
        //设置各个控件的点击响应
        mGroupSelectList = (ListView) contentView.findViewById(R.id.group_pop_list);
        mGroupSelectList.setAdapter(mGroupSelectItemAdapter);
        mGroupSelectList.setOnItemClickListener(this);

        //显示PopupWindow
        View rootView = LayoutInflater.from(EditActivity.this).inflate(R.layout.activity_group_list, null);
        mPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Group group = mGroups.get(i);
        mGroupId = group.getId();
        if (mGroupId != -1){
            mGroupSelect.setText(group.getName());
        } else {
            mGroupSelect.setText("");
            mGroupId = null;
        }
        mPopWindow.dismiss();
    }
}
